package com.ligq.h265toupinpush.call

import android.content.Context
import android.hardware.Camera
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView

class LocalSurfaceView(
    context: Context?,
    attrs: AttributeSet?,
    defStyleAttr: Int,
    defStyleRes: Int
) : SurfaceView(context, attrs, defStyleAttr, defStyleRes), SurfaceHolder.Callback,
    Camera.PreviewCallback {
    private lateinit var mCamera: Camera
    lateinit var size: Camera.Size

    constructor(context: Context?) : this(context, null)

    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : this(
        context,
        attrs,
        defStyle,
        0
    )

    init {
        holder.addCallback(this)
    }

    private fun startPreview() {
        mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT)
        val parameters = mCamera.parameters
        size = parameters.previewSize
        try {
            mCamera.setPreviewDisplay(holder)
            mCamera.setDisplayOrientation(90)
            val buffer = ByteArray(size.width * size.height * 3 / 2)
            mCamera.addCallbackBuffer(buffer)
            mCamera.setPreviewCallback(this)
            mCamera.startPreview()
        } catch (e: Exception) {
            Log.e(com.ligq.h265toupinpush.toupin.TAG, "startPreview: ", e)
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        startPreview()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {

    }

    //相机的数据进行编码然后传输 NV21数据
    override fun onPreviewFrame(data: ByteArray?, camera: Camera?) {
        if (this::encoder.isInitialized) {
            encoder.encodeFrame(data!!)
        }
        mCamera.addCallbackBuffer(data)
    }

    private lateinit var encoder: EncodeH264LivePush

    fun startCapture(socketLive: SocketLive) {
        encoder = EncodeH264LivePush(size.width, size.height, socketLive)
        encoder.startLive()
    }
}